package com.ler.auth.filter;

import cn.hutool.core.convert.Convert;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.ler.yrmall.dto.UserDTO;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.authority.AuthorityUtils;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.web.authentication.WebAuthenticationDetailsSource;
import org.springframework.web.filter.OncePerRequestFilter;

import javax.servlet.FilterChain;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.List;

/**
 * @author leron
 */
public class TokenAuthFilter extends OncePerRequestFilter {
    @Override
    protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain filterChain) throws ServletException, IOException {
        String userStr = request.getHeader("user");
        if (userStr != null) {
            JSONObject userJsonObject = JSON.parseObject(userStr);
            UserDTO userDTO = new UserDTO();
            String principal = userJsonObject.getString("user_name");
            long id = userJsonObject.getLongValue("id");
            List<String> authorities = Convert.toList(String.class, userJsonObject.get("authorities"));
            userDTO.setUsername(userJsonObject.getString(principal));
            userDTO.setId(id);
            userDTO.setUsername(principal);
            userDTO.setRoles(authorities);
            UsernamePasswordAuthenticationToken credentials = new UsernamePasswordAuthenticationToken(userDTO,null, AuthorityUtils.createAuthorityList(authorities.toArray(new String[0])));
            credentials.setDetails(new WebAuthenticationDetailsSource().buildDetails(request));
            SecurityContextHolder.getContext().setAuthentication(credentials);
        }
        filterChain.doFilter(request,response);
    }
}
